﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.DataVisualization.Charting;
using Tfs.OnTheRoad.ViewModel;
using System.Collections.Generic;
using Tfs.OnTheRoad.Controls.ChartStrategies;
using System.Windows.Media;
using Microsoft.Phone.Controls;

namespace Tfs.OnTheRoad.Controls
{
    /// <summary>
    /// Reusable WorkItems Chart Control
    /// DataContext should be a WorkItemsChartViewModel
    /// </summary>
	public partial class WorkItemsOverviewChartControl : UserControl
	{        
        public WorkItemsOverviewChartControl()
		{
			// Required to initialize variables
			InitializeComponent();
		}

        void ViewModel_ChartDataPrepared(object sender, EventArgs e)
        {
            ViewModel.CurrentChartStrategy.SetupChart(workItemsChart, ViewModel.WorkItemsSummary);
            if (!Saved)
            {
                //We only save when everything went ok during the chart customization
                Helpers.SettingsStorageHelper.SaveChartSettings(ViewModel.CurrentChartStrategy, ViewModel.ChartSettingsName);
                Saved = true;
            }
        }
               
        private WorkItemsChartViewModel ViewModel;
       
        private void ChartControl_Loaded(object sender, RoutedEventArgs e)
        {
            ViewModel = this.DataContext as WorkItemsChartViewModel;
            if(ViewModel!=null)
                ViewModel.ChartDataPrepared += new EventHandler(ViewModel_ChartDataPrepared);  
        }
        private bool Saved = true;
        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            BaseChartStrategy newStrategy = (BaseChartStrategy)chartTypePicker.SelectedItem;
            newStrategy.Field1 = field1Picker.SelectedItem.ToString();
            if (newStrategy.IsStacked)
                newStrategy.Field2 = field2Picker.SelectedItem.ToString();
            else
                newStrategy.Field2 = null;
            ViewModel.CurrentChartStrategy = newStrategy;
            ViewModel.CalculateSummary();
            Saved = false;
        }


        public bool IsSettingsVisible
        {
            get
            {
                return ChartSettingsPane.Visibility==System.Windows.Visibility.Visible;
            }
        }
    }
}